$(document).ready(function(){
    // 初始时的控件的值
    var cityId = $("#cname").val();
    var areaId = $("#qname").val();
    var streetId = $("#jname").val();
    var html = "";

    function ref_component_base(curr_change_id, title, each_var, b_id, curr_id, html_val, op_attr_id, op_attr_name){
        if (curr_change_id != '-1') {
            // 区域
            html = "<option value='-1'>" + title + "</option>";
            $.each(each_var, function(a,b){
                if (b[b_id] == curr_change_id) {
                    if ( curr_id != '-1' && curr_id == b[op_attr_id] ) {
                        html += "<option value='" + b[op_attr_id] + "' selected='selected'>" + b[op_attr_name] + "</option>"
                    } else {
                        html += "<option value='" + b[op_attr_id] + "'>" + b[op_attr_name] + "</option>"
                    }
                };
            });
            $("#" + html_val).html(html);
        } else {
            html = "<option value='-1'>" + title + "</option>";
            $("#" + html_val).html(html);
        }
    }

    function ref_component(){
        ref_component_base(cityId, "请选择城市", allCity, 'provincecode', areaId, "qname", 'code', 'name');
        ref_component_base(areaId, "请选择分区", allArea, 'citycode', streetId, "jname", 'code', 'name');
    }

    ref_component();
    
    // 城市有变化
    $("#cname").bind("change",function(){ 
        cityId = $("#cname").val();
        areaId = '-1';
        streetId = '-1';
        shequId = '-1';
        ref_component();
    });

    // 区域有变化
    $("#qname").bind("change",function(){
        areaId = $("#qname").val();
        streetId = '-1';
        shequId = '-1';
        ref_component();
    });

});
